/*
 * 文 件 名 : LeaveMessage.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2013-1-23
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.diary;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.model.Answer;
import com.fire8.dolphin.service.SubmitAnswer;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.more.ApplyServerActivity;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;

/**
 * 评论页面
 * <功能详细描述>
 *
 * @author  lixg
 * @version [版本号,2013-1-23]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class ReviewActivity extends Activity
{

    private EditText txtContext;
    private Button btnEnter;//保存
    
    private Button btnInputVoice;//切换到语音输入页面
    private Button btnInputText;//切换到文字输入页面
    private ImageView imgInputVoice;//按住说话的MIC图片
    
    private ImageView imgPlayVoice;//显示回放按钮
    private RelativeLayout layInputVoice;//语音输入布局
    
    private String strContext;
    DolphinApplication app;
    
    private MediaRecorder mRecorder = null;
    private File mRecAudioPath;
    private File mRecAudioFile;
    private long startTime;//录音开始时间
    private long endTime;//录音结束时间
    private long voiceLong;//录音时长(秒)
    
    private String qRemoteId;
    private String qUserId;
    private ProgressDialog progressDialog = null;
    private AnimationDrawable voicePlayAnim;//播放动画
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_add);
        qRemoteId = getIntent().getStringExtra("qRemoteId");
        qUserId = getIntent().getStringExtra("qUserId");
        findViewById(R.id.btn_input_img).setVisibility(View.GONE);//隐藏图片输入面板
        findViewById(R.id.txt_title).setVisibility(View.GONE);//隐藏标题输入框
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.fire8.dolphin.ui.diary.ReviewActivity");
        filter.addAction(Constants.VOICE_PLAY_CALLBACK);
        registerReceiver(receiver, filter);
        txtContext = (EditText)findViewById(R.id.txt_context);
        btnEnter = (Button)findViewById(R.id.btn_enter);
        btnEnter.setOnClickListener(new ButtonClickLienter());
        app = (DolphinApplication)getApplication();
        layInputVoice = (RelativeLayout)findViewById(R.id.lay_input_voice);
        
        btnInputText = (Button)findViewById(R.id.btn_input_txt);
        
        imgPlayVoice = (ImageView)findViewById(R.id.img_play_voice);
        btnInputVoice = (Button)findViewById(R.id.btn_input_voice);
        imgInputVoice = (ImageView)findViewById(R.id.img_input_voice);
        
        btnInputVoice.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                btnInputVoice.setBackgroundResource(R.color.tab_bg_gray_1);
                
                btnInputText.setBackgroundResource(R.color.tab_bg_gray);
                
                layInputVoice.setVisibility(View.VISIBLE);
                txtContext.setVisibility(View.GONE);
            }
        });
        btnInputText.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                btnInputText.setBackgroundResource(R.color.tab_bg_gray_1);
                btnInputVoice.setBackgroundResource(R.color.tab_bg_gray);
                
                layInputVoice.setVisibility(View.GONE);
                txtContext.setVisibility(View.VISIBLE);
            }
        });
        imgInputVoice.setOnLongClickListener(new OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v)
            {
                startRecording();
                return false;
            }
        });
        imgInputVoice.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if(MotionEvent.ACTION_UP == event.getAction())
                {
                    //停止录音
                    stopRecording();
                    
                    if(mRecAudioFile != null)
                    {
                        LogUtil.d("完成录音： "+mRecAudioFile.getPath());
                        LogUtil.d("文件大小(字节)："+mRecAudioFile.length());
                        imgPlayVoice.setVisibility(View.VISIBLE);
                        imgPlayVoice.setBackgroundResource(R.anim.voice_play_w);
                    }
                    
                }
                return false;
            }
        });
        //回放按钮
        imgPlayVoice.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                
                if(mRecAudioFile != null)
                {
                    voicePlayAnim = (AnimationDrawable)imgPlayVoice.getBackground();
                    if(voicePlayAnim.isRunning())
                    {
                        imgPlayVoice.setImageResource(R.drawable.play3_w);
                        voicePlayAnim.stop();
                        sendMessage(Constants.MEDIA_PAUSE,"");
                    }else
                    {
                        imgPlayVoice.setImageDrawable(null);
                        voicePlayAnim.start();
                        sendMessage(Constants.MEDIA_INIT,mRecAudioFile.getPath());
                    }
                    LogUtil.d("播放录音");
                    //imgPlayVoice.setImageBitmap(null);
                    //启动任务，播放语音、显示动画
                    
                    //VoiceAnimAndPlay task = new VoiceAnimAndPlay();
                    //task.execute(mRecAudioFile.getPath());
                }
            }
        });
    }
    //==================================================================================
    private void startRecording() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                mRecAudioPath = Environment.getExternalStorageDirectory();
                File fPath = new File(mRecAudioPath.getPath() + File.separator
                                + "RecordList");
                fPath.mkdirs();
                LogUtil.d("创建文件夹"+fPath.getPath());
                mRecAudioFile = fPath;
        } else {
            mRecAudioFile = this.getCacheDir();    
            LogUtil.d("没有插卡或没有读写卡权限，创建文件夹");
        }
        try {
                mRecAudioFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".3gp", mRecAudioFile);
                LogUtil.d("创建文件： "+mRecAudioFile.getPath());
        } catch (IOException e) {
            LogUtil.e("mRec", e);
        }
        
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mRecAudioFile.getPath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
            mRecorder.start();
            startTime = System.currentTimeMillis();
            LogUtil.d("开始录音...");
        } catch (IOException e) {
            LogUtil.e( "prepare() failed",e);
        }
        
        
    }
    private void stopRecording() {
        if(mRecorder == null)
            return;
        //if(mRecorder.)
        mRecorder.stop();
        endTime = System.currentTimeMillis();
        voiceLong = (endTime-startTime)/1000;
        mRecorder.release();
        mRecorder = null;
        
        LogUtil.d("停止录音...");
        LogUtil.d(voiceLong+"秒");
    }
    /**确定按钮，上传回复到网上**/
    class ButtonClickLienter implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            String context = txtContext.getText().toString();
            if(mRecAudioFile != null || !StringUtil.isEmpty(context))
            {
                //显示进度条
                progressDialog = ProgressDialog.show(ReviewActivity.this, "请稍等...", "正在提交...", true);
                saveAnswer(context);
                
            }
        }
    }
    private void saveAnswer(String context)
    {
        Answer answer = new Answer();
        //answer.setqId(locId);
        answer.setqRemoteId(qRemoteId);
        answer.setaContext(context);
        answer.setUpdateDate(DateUtil.dateToStr(new Date(),
                "yyyy-MM-dd HH:mm:ss"));
        answer.setUserId(app.getUserId());
        answer.setUserName(app.getUserName());
        answer.setUserHead(app.getUserHead());
        if(mRecAudioFile != null)
        {
            answer.setVoiceLong(voiceLong);
            answer.setVoice(mRecAudioFile.getPath());
        }
        if (app.getUserId().equals(qUserId))
        {
            answer.setaType(Answer.ANSWER_TYPE_SELF);
        }
        else
        {
            answer.setaType(Answer.ANSWER_TYPE_UNSELF);
        }
        //调用service提交回答到服务器
        SubmitAnswer submit = new SubmitAnswer(this, app);
        submit.execute(answer);
        
    }
    /**接收提交结果信息**/
    BroadcastReceiver receiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if(intent.getAction().equals("com.fire8.dolphin.ui.diary.ReviewActivity"))
            {
                if(progressDialog != null)progressDialog.dismiss();
                boolean flag = intent.getBooleanExtra("success", false);
                if(flag)
                {
                    ReviewActivity.this.finish();
                }
            }else if(intent.getAction().equals(Constants.VOICE_PLAY_CALLBACK))
            {
                int commend = intent.getIntExtra("command", 0);
                switch (commend)
                {
                    case Constants.MEDIA_INIT:
                        //初始化完成,已经开始播放，修改播放状态
                        
                        break;
                    case Constants.MEDIA_START:
                        //启动动画
                        if(!voicePlayAnim.isRunning())
                        {
                            imgPlayVoice.setImageDrawable(null);
                            voicePlayAnim.start();
                        }
                        break;
                    case Constants.MEDIA_PAUSE:
                        
                        if (voicePlayAnim != null)
                        {
                            imgPlayVoice.setImageResource(R.drawable.play3_w);
                            voicePlayAnim.stop();
                        }
                        break;
                    case Constants.MEDIA_STATUS_STOP:
                        //播放完成，修改播放状态
                        if (voicePlayAnim != null)
                        {
                            imgPlayVoice.setImageResource(R.drawable.play3_w);
                            voicePlayAnim.stop();
                        }
                        break;
                    default:
                        break;
                }
            }
            
        }
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    /**发送控制指令播或停止语音**/
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.VOICE_PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
}
